package com.example.customview.util

import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.util.DisplayMetrics
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.widget.NestedScrollView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import com.example.customview.adapter.ListAdapter
import com.example.customview.bean.SegmentDataBean
import com.example.customview.bean.TableBean
import com.example.customview.bean.ViewDataBean
import com.example.modulejsonui.R
import com.example.modulejsonui.bean.ItemViewBean
import com.example.modulejsonui.bean.NaviDataBean
import com.example.modulejsonui.bean.TableDataBean
import com.example.modulejsonui.fragment.SonFragment
import com.example.modulejsonui.fragment.SonInsideFragment
import com.example.modulejsonui.util.CommonJSONParserUtil
import com.example.modulejsonui.util.ComposeViewUtil
import com.example.modulejsonui.util.ScreenUtil
import com.google.android.material.tabs.TabLayout


/**
 * Created by Android Studio.
 * User: wsl
 * Date: 7/22/21
 * Time: 4:37 PM
 * Description: Layout 布局返回
 */
class LayoutUtils {
    companion object instance {
        //宽高 填充
        fun setMatlayoutParams(): RelativeLayout.LayoutParams{
            return RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT,
                    RelativeLayout.LayoutParams.MATCH_PARENT)
        }

           //宽高 填充
        fun setMatlayoutParams(s: Int): RelativeLayout.LayoutParams{
            return RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        }


        fun  setNestedScrollView(context: Context):NestedScrollView{
            var nestedScrollview = NestedScrollView(context)
            nestedScrollview.layoutParams = setMatlayoutParams()

            return nestedScrollview
        }


        fun setRelativeLayout(mContext: Context):RelativeLayout{
            var relativeLayout = RelativeLayout(mContext)
            relativeLayout.layoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
            val gradientDrawable = GradientDrawable()
//            gradientDrawable.shape = GradientDrawable.RECTANGLE
//            gradientDrawable.setColor(Color.parseColor(bean.backgroundColor))

            relativeLayout.background =gradientDrawable

            return relativeLayout

        }

        fun setConstraintLayout(mContext: Context): ConstraintLayout {
            var relativeLayout = ConstraintLayout(mContext)
            relativeLayout.layoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            val gradientDrawable = GradientDrawable()
//            gradientDrawable.shape = GradientDrawable.RECTANGLE
//            gradientDrawable.setColor(Color.parseColor(bean.backgroundColor))

            relativeLayout.background =gradientDrawable

            return relativeLayout

        }



        @SuppressLint("WrongConstant")
        fun setLinearLayout(context: Context): LinearLayout? {
            val linear = LinearLayout(context)
            linear.layoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
            linear.orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

            return linear
        }


        @SuppressLint("WrongConstant")
        fun setLinearLayout(context: Context, type: Int): LinearLayout? {
            val linearLayout = LinearLayout(context)
//        constraintLayout.id = R.id.clRoot
            linearLayout.layoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
//            constraintLayout.orientation =LinearLayout.VERTICAL // 垂直
//            constraintLayout.orientation =LinearLayout.HORIZONTAL// 水平
            linearLayout.orientation = type
            return linearLayout
        }



        /**
         * 添加标题View
         */
        fun setTitleViewData(mContext: Context, bean: NaviDataBean.NaviDataBean):CoordinatorLayout{
            var layout = CoordinatorLayout(mContext)
            layout.id = R.id.coordinatorLayout
            val gradientDrawable = GradientDrawable()
//            gradientDrawable.shape = GradientDrawable.RECTANGLE
            gradientDrawable.setColor(Color.parseColor(bean.backgroundColor))
            layout.background = gradientDrawable

            layout.setPadding(0, 25, 0, 0)

//            var lp1 = setMatlayoutParams(1)
//            lp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT)
            var lp1 =  RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DrawableUtil.dp2px(mContext, 66f))
//            layout.layoutParams = lp1

            if(bean.rightView !=null){
//                val lp =   RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,DrawableUtil.dp2px(mContext, 66f))
//                lp1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE)// 设置文字靠右展示

//                lp1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);

                layout.addView(ViewAddUtils.addTextView(mContext, bean.rightView.labelData))

            }
            if(bean.leftView !=null){
                var img= ViewAddUtils.addImgView(mContext, bean.leftView.imageData)
                layout.addView(img)
            }
            layout.layoutParams = lp1

            return layout
        }

        /**
         * 模块View
         */
        fun setPlateView(mContext: Context, list: MutableList<NaviDataBean.ViewBean>,jsonMap: MutableMap<String, String>):CoordinatorLayout{
            var coordinatorLayout = CoordinatorLayout(mContext)
            coordinatorLayout.layoutParams = ViewAddUtils.setWplayoutParams()
            var linearLayout = setLinearLayout(mContext, LinearLayout.VERTICAL)
            for ( bean: NaviDataBean.ViewBean in list){
                when(bean.type){
                    0 -> {
                        coordinatorLayout?.addView(ViewAddUtils.addTextView(mContext, bean.labelData))
                    }
                    1 -> {
                        coordinatorLayout?.addView(ViewAddUtils.addButtonView(mContext, bean.buttonData)) //这里赋值还需要改动
                    }
                    2 -> {
                        coordinatorLayout?.addView(ViewAddUtils.addImgView(mContext, bean.imageData))
                    }
                    3 -> {
                        linearLayout?.addView(ComposeViewUtil.getIntegralTopView(mContext, bean.viewData, jsonMap[bean.jsonData].toString()))
//                        linearLayout?.addView(ViewAddUtils.addVIew(mContext, bean.viewData))
                    }
                }
            }
            coordinatorLayout?.addView(linearLayout)
            return coordinatorLayout

        }

        /**
         *给Adpter添加背景
         */
        fun setAdpaterSonTopView(context: Context,viewData: TableDataBean): CoordinatorLayout {
            var mCoordinatorLayout = CoordinatorLayout(context)

            val layoutparams =   RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT, DrawableUtil.dp2px(context, viewData.layout.height.toFloat()))

            if(viewData.publicAtt.cornerRadius !=0){
                val gradientDrawable = GradientDrawable()
                gradientDrawable.shape = GradientDrawable.RECTANGLE
                gradientDrawable.setColor(Color.parseColor(viewData.publicAtt.backgroundColor))
                gradientDrawable.cornerRadius = viewData.publicAtt.cornerRadius!!.toFloat()
                mCoordinatorLayout.background = gradientDrawable
            }

            layoutparams.topMargin = DrawableUtil.dp2px(context,viewData.layout.top.toFloat())
            layoutparams.leftMargin = DrawableUtil.dp2px(context,viewData.layout.left.toFloat())
            layoutparams.rightMargin = DrawableUtil.dp2px(context,viewData.layout.right.toFloat())

             mCoordinatorLayout?.addView (addAdpterView(context,viewData.items[0].viewData,""))
            mCoordinatorLayout.layoutParams = layoutparams

            return mCoordinatorLayout
        }

        /**
         * 给Item 添加适配器view
         */
        fun addAdpterView(context: Context, bean : ViewDataBean, dataString:String) :RecyclerView{
            val recyclerView = RecyclerView(context)
            val tvRightLayoutParams =     RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT)

//            tvRightLayoutParams.marginStart =16// ScreenUtil.dpToPx(this, 16)
//            tvRightLayoutParams.topMargin = 16//ScreenUtil.dpToPx(context, 16)
            recyclerView.setPadding(DrawableUtil.dp2px(context, bean.layout.left.toFloat()), DrawableUtil.dp2px(context, bean.layout.top.toFloat()),
                    DrawableUtil.dp2px(context, bean.layout.right.toFloat()), DrawableUtil.dp2px(context, bean.layout.bottom.toFloat()))

            recyclerView.layoutParams = tvRightLayoutParams
            recyclerView.overScrollMode = View.OVER_SCROLL_NEVER

            if(dataString!=null && dataString!="null"){
                var map = CommonJSONParserUtil.parse(
                        CommonJSONParserUtil.removeQuotation(dataString.replace("\\","")))
               var mList =  map!![bean.jsonDataKey]
                Log.i("layoutUtils",mList.toString())
                InitAdapter(context,recyclerView,bean.subItem, mList as MutableList<HashMap<String, String>>)
            }


            return recyclerView
        }

        fun InitAdapter(context: Context,recycler :RecyclerView,bean: MutableList<ItemViewBean>,mList :  MutableList<HashMap<String,String>> ){
//            var mList :  MutableList<HashMap<String,String>> =ArrayList()

            var mListAdapter = ListAdapter(context,bean)
            val layoutManager = GridLayoutManager(context, 1)
            recycler.layoutParams = setMatlayoutParams()
            recycler.layoutManager = layoutManager
            recycler.adapter = mListAdapter

//            for (index in 1..3){
//                mList.add(index.toString())
//            }
            mListAdapter.data = mList
            mListAdapter?.notifyDataSetChanged()
        }

        /**
         * 设置整块layout UI
         */
        fun addFragmentView(bean: SegmentDataBean,mContext: Context,mFragmentManager : FragmentManager): CoordinatorLayout {
            var tabLayout = ViewAddUtils.addTabLayout(mContext,0f,bean.segmented)
            var viewPager =  ViewAddUtils.addViewPager(mContext,R.id.viewPager)

            var layout =  setLinearLayout(mContext)
            layout?.addView(setViewItem(mContext,bean.header))//添加顶部数据

            layout?.addView(tabLayout)
            layout?.addView(viewPager)

            var coord = ViewAddUtils.setCoordinatorLayout(mContext)

            coord.addView(layout)
            setTabLayout(tabLayout, viewPager, bean.list,mContext,mFragmentManager)
            return coord
        }

        fun setViewItem(mContext: Context, beans: MutableList<ItemViewBean>):CoordinatorLayout{
            val coordinator= CoordinatorLayout(mContext)
            coordinator.layoutParams = ViewAddUtils.setWplayoutParams()
            for ( bean: ItemViewBean in beans){
                when(bean.type){
                    0 -> {
                        coordinator?.addView(ViewAddUtils.addTextView(mContext, bean.labelData))
                    }
                    1 -> {
//                        coordinator?.addView(ViewAddUtils.addButtonView(mContext, bean.imageData)) //这里赋值还需要改动
                    }
                    2 -> {
                        coordinator?.addView(ViewAddUtils.addImgView(mContext, bean.imageData))
                    }
                    3 -> {
                        coordinator?.addView(ViewAddUtils.addVIew(mContext,bean.viewData))
                    }
                }
            }
            return coordinator
        }

        /**
         * 设置tabLayout 联动
         */
        fun setTabLayout(tabLayout: TabLayout, viewPager: ViewPager, mList: MutableList<SegmentDataBean.ListBean>,mContext: Context,mFragmentManager : FragmentManager){
            tabLayout.tabGravity = TabLayout.GRAVITY_FILL
            tabLayout.tabMode = TabLayout.MODE_FIXED

            var fragmentList: MutableList<Fragment> = ArrayList()
            var tabs: MutableList<String> = ArrayList()

            for (bean in mList){
                fragmentList.add(SonFragment(mContext,bean))
                tabs.add(bean.title)
            }

            viewPager.findViewById<ViewPager>(R.id.viewPager).adapter = object : FragmentPagerAdapter(mFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
                override fun getItem(position: Int): Fragment {
                    return fragmentList[position]
                }
                override fun getCount(): Int {
                    return fragmentList.size
                }
                override fun getPageTitle(position: Int): CharSequence? {
                    return tabs[position]
                }
            }
            //设置TabLayout和ViewPager联动
            tabLayout.setupWithViewPager(viewPager, false)

        }

        /**
         * 添加子fragment
         */
        fun addFragmentSonView(bean:SegmentDataBean.ListBean, mContext: Context, mFragmentManager : FragmentManager): CoordinatorLayout {
            var tabLayout = ViewAddUtils.addTabLayout(mContext,0f,bean.segmented)
            var viewPager =  ViewAddUtils.addViewPager(mContext,R.id.viewPager1)

            var layout =  setLinearLayout(mContext)
            layout?.addView(tabLayout)
            layout?.addView(viewPager)
            var coord = ViewAddUtils.setCoordinatorLayout(mContext)

            coord.addView(layout)
            setSonTabLayout(tabLayout, viewPager, bean,mContext,mFragmentManager)
            return coord
        }

        /**
         * 添加子view的
         */
        fun setSonTabLayout(tabLayout: TabLayout, viewPager: ViewPager, mList: SegmentDataBean.ListBean, mContext: Context, mFragmentManager : FragmentManager){
            tabLayout.tabGravity = TabLayout.GRAVITY_FILL
            tabLayout.tabMode = TabLayout.MODE_FIXED

            var fragmentList: MutableList<Fragment> = ArrayList()
            var tabs: MutableList<String> =  ArrayList()
//            tabs.add(bean.title)

            for (bean in mList.segmentTitles){
                fragmentList.add(SonInsideFragment(mContext,mList?.controllers))
                tabs.add(bean)
            }

            viewPager.findViewById<ViewPager>(R.id.viewPager1).adapter = object : FragmentPagerAdapter(mFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
                override fun getItem(position: Int): Fragment {
                    return fragmentList[position]
                }
                override fun getCount(): Int {
                    return fragmentList.size
                }
                override fun getPageTitle(position: Int): CharSequence? {
                    return tabs[position]
                }
            }
            //设置TabLayout和ViewPager联动
            tabLayout.setupWithViewPager(viewPager, false)

        }

        /**
         * 添加ITEM UI
         */
        @SuppressLint("NewApi")
        fun  addRecyclerView(mContext:Context,bean : MutableList<TableBean>):RelativeLayout{
            var constart =  setRelativeLayout(mContext)
            val recyclerView = RecyclerView(mContext?.applicationContext!!)

            recyclerView.id = R.id.recyclerView
            val tvRightLayoutParams = setMatlayoutParams()

            tvRightLayoutParams.marginStart =16// ScreenUtil.dpToPx(this, 16)
            tvRightLayoutParams.topMargin = 16//ScreenUtil.dpToPx(this, 16)

            recyclerView.layoutParams = tvRightLayoutParams
            constart.addView(recyclerView)

            InitAdapter(recyclerView,bean,mContext)
            return constart
        }

        private fun InitAdapter(recycler: RecyclerView,mBean : MutableList<TableBean>,mContext:Context){
            var mList :  MutableList<HashMap<String,String>> =ArrayList()

            if(mBean !=null && mBean?.size !=0){
                var mListAdapter = ListAdapter(mContext?.applicationContext!!, mBean?.get(0)?.listData?.items!!)
                val layoutManager = GridLayoutManager(mContext, 1)
                recycler.layoutParams = setMatlayoutParams()
                recycler.layoutManager = layoutManager
                recycler.adapter = mListAdapter

//                for (index in 1..10){
//                    mList.add(index.toString())
//                }
                mListAdapter.data = mList
                mListAdapter?.notifyDataSetChanged()
            }
        }


    }

}